//
//  DHStatusListViewModel.swift
//  Weibo
//
//  Created by Holfioo on 15/9/7.
//  Copyright © 2015年 Holfioo. All rights reserved.
//

import UIKit
import ReactiveCocoa
import SDWebImage

class DHStatusListViewModel: NSObject {
    
    lazy var statuses = [DHStatusViewModel]()
    
    func loadData(isPullupRefresh isPullupRefresh: Bool) -> RACSignal {
        // 上拉刷新和下拉刷新的赋值
        var since_id = (statuses.count ?? 0) == 0 ? 0 : statuses.first?.status.id
        var max_id = 0
        if isPullupRefresh {
            since_id = 0
            max_id = statuses.last!.status.id
        }
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            DHRequestTool.shareTool.loadStatus(since_id: since_id!, max_id: max_id).subscribeNext({ (result) -> Void in
                // 用守卫方法
                // 注意是 字典数组。[字典]  字典：[String: AnyObject]
                guard let ViewModel = result["statuses"] as? [[String: AnyObject]] else {
                    print("未加载到数据")
                    // 无数据 程序直接返回
                    subscriber.sendError(NSError(domain: "holf‘s", code: -1023, userInfo: ["noViewModel" : "网络无数据"]))
                    return
                }
                // 字典转模型
//                if self.statuses == nil {
//                    self.statuses = [DHStatusViewModel]()
//                }
                // 字典转模型，增加到当前的模型数组中
                var arrM = [DHStatusViewModel]()
                
                // 中间有视图模型。
                for dict in ViewModel {
                    arrM.append(DHStatusViewModel(status: DHStatus(dict: dict)))
                }
                printLog("刷新到\(arrM.count)条微博")
                self.cacheImage(arrM) {
                    // 讲变量赋值给
                    if since_id > 0 {
                        self.statuses = arrM + self.statuses
                    } else {
                      self.statuses += arrM
                    }
                    
                    // printLog(self.statuses)
                    // 完成
                    // subscriber.sendNext(<#T##value: AnyObject!##AnyObject!#>)
                    subscriber.sendCompleted()
                }
                
                }, error: { (error) -> Void in
                    // 发送错误
                    subscriber.sendError(error)
                }) {}
            return nil
        })
    }
    // 保存图片
    private func cacheImage(array: [DHStatusViewModel], finish: () -> ()) {
//        printLog(array)
        // 创建调度组
        let group = dispatch_group_create()
        
        var dataLength = 0
        
        for viewModel in array {
            // 只需要存单张图片
            let count = viewModel.thumbnailUrls?.count ?? 0
            // 过滤非单张图片
            if count != 1 {
                continue // 继续遍历下一个
            }
            
            // printLog(viewModel.thumbailUrls)
            // 入组要紧贴着闭包。成对出现
            dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(viewModel.thumbnailUrls![0], options: [], progress: nil, completed: { (image, _, _, _, _) -> Void in
                // 查看一共图片大小
                
                if image != nil {
                let data = UIImagePNGRepresentation(image)
                
                dataLength += data?.length ?? 0
                // 出组在闭包的最后一句！
                }
                dispatch_group_leave(group)
            })
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            // 监听。
            printLog("图片缓存完成\(dataLength/1024)k")
            finish()
        }
    }
}
